"use strict";

import axios from "axios";
import { ElLoading  } from "element-plus";
import { sessionGet } from "../utils/auth";


let config = {
  baseURL: conf.baseURL,
  timeout: 30 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
  method: "post",
  headers: {
    "Content-Type": "application/json;charset=UTF-8",
  },
};
let loadingInstance = null;
export const Service = axios.create(config);

Service.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    loadingInstance = ElLoading.service({
      lock: true,
      text: "请稍后...",
    });
    //身份认证相关设置
    const token = sessionGet('token');
    token && (config.headers.token = token);
    return config;
  },
  function (error) {
    if (loadingInstance) {
      loadingInstance.close();
    }
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
Service.interceptors.response.use(
  function (response) {
    if (loadingInstance) {
      loadingInstance.close();
    }
    if (response["data"]["code"] === 401) {
      //401 退出到登录页面，如在session或localstorage 存储有数据，务必删除
      this.$router.replace({ name: "Login" });
    } else {
      return response.data;
    }
    // Do something with response data
    return response;
  },
  function (error) {
    if (loadingInstance) {
      loadingInstance.close();
    }
    return Promise.reject(error);
  }
);
